# coding:utf-8

import commands
from vle.vleApp.models import AnsweredQuiz, Student, FeedbackComment
from django.shortcuts import render_to_response
from vle.vleApp.models import Post, Thread, Video, File, News, ConstantVariables, PostUserVote
from vle.vleApp.models import Student, Course, Group, Teacher, StudentGradeIndex, Avatar
from django.contrib.auth.models import User, Permission
from django.contrib.auth.models import Group as DjangoGroup
from django.core.files.images import get_image_dimensions
from django.core.mail import send_mail
from django.db.models import Q
from itertools import chain
from django.http import HttpResponse

from info import getUserMail
from django.core.mail import EmailMessage
import time
import threading
import os.path
import datetime
import traceback
import xlrd
import random

def updateDictWithGeneralVars(request,dict):
    admin=request.user.is_superuser

    try:
        student=request.user.groups.values()[0]['name'] == "Students"
        teacher=request.user.groups.values()[0]['name'] == "Teachers"
    except:
        student=False
        teacher=False

    #get user groups
    userGroups = getGroupsForUser(request.user)

    #get avatar
    if student:
        avatar=Student.objects.get(id=request.user.id).avatar
    if teacher:
        avatar=Teacher.objects.get(id=request.user.id).avatar

    if student or teacher:
        avatarPath=avatar.path
        (width,height)=resizeDimensionsW(avatar.width,avatar.height,150)

    else:
        avatarPath="/resources/avatars/default_avatar.jpg"
        width="100"
        height="150"
    user = request.user if request.user.is_authenticated() else None
    addedDict={'user':user,
                'avatar':[avatarPath,width,height],
                'isStudent':student,
                'isTeacher':teacher,
                'isAdmin':admin,
                'groupList':userGroups}
    dict.update(addedDict)
    return dict

def resizeDimensionsW(width,height,maxWidth,hasToBeMaxWidth=False):
    if width>maxWidth:
        reducedWidth=width-maxWidth
        newHeight=height-int(height*reducedWidth/width)
        width=maxWidth
        height=newHeight
    if hasToBeMaxWidth:
        if width<maxWidth:
            aumentedWidth=maxWidth-width
            newHeight=height+int(height*aumentedWidth/width)
            width=maxWidth
            height=newHeight
    return (width,height)

def resizeDimensionsH(width,height,maxHeight,hasToBeMaxHeight=False):
    if height>maxHeight:
        reducedHeight=height-maxHeight
        newWidth=width-int(width*reducedHeight/height)
        height=maxHeight
        width=newWidth
    if hasToBeMaxHeight:
        if height<maxHeight:
            aumentedHeight=maxHeight-height
            newWidth=width+int(width*aumentedHeight/height)
            height=maxHeight
            width=newWidth
    return (width,height)

def resizeDimensionsWH(width,height,maxWidth,maxHeight,hasToBeMaxWidth=False,hasToBeMaxHeight=False):
    if hasToBeMaxWidth and hasToBeMaxHeight:
        return (maxWidth,maxHeight)
    if hasToBeMaxWidth:
        return resizeDimensionsW(width,height,maxWidth,hasToBeMaxWidth)
    if hasToBeMaxHeight:
        return resizeDimensionsH(width,height,maxHeight,hasToBeMaxHeight)

    (x,y)=resizeDimensionsW(width,height,maxWidth,hasToBeMaxWidth)
    (x2,y2)=resizeDimensionsH(x,y,maxHeight,hasToBeMaxWidth)
    return (x2,y2)

def getGroupActivity(groupCode,courseCode,numEntries):
    courseModel=Course.objects.get(code=courseCode)
    grp=Group.objects.get(code=groupCode,course=courseModel)
    threadList=Thread.objects.filter(group=grp)
    postList=Post.objects.filter(thread__in=threadList)
    videoList=Video.objects.filter(groups=grp)
    fileList=File.objects.filter(groups=grp)
    newsList=News.objects.filter(groups=grp)

    activityList = sorted(chain(threadList,postList,videoList,fileList,newsList),key=lambda instance: instance.date)

    truncatedList=activityList[::-1][0:numEntries]

    formattedList=[]
    for element in truncatedList:
        if isinstance(element,Thread):
            formattedList.append(["Thread",element])
        if isinstance(element,Post):
            formattedList.append(["Post",element])
        if isinstance(element,Video):
            formattedList.append(["Video",element])
        if isinstance(element,File):
            formattedList.append(["File",element])
        if isinstance(element,News):
            formattedList.append(["News",element])
    return formattedList

def getForumActivity(groupCode,courseCode,numEntries):
    courseModel=Course.objects.get(code=courseCode)
    grp=Group.objects.get(code=groupCode,course=courseModel)
    threadList=Thread.objects.filter(group=grp)
    postList=Post.objects.filter(thread__in=threadList)
    activityList = sorted(chain(threadList,postList),key=lambda instance: instance.date)

    truncatedList=activityList[::-1][0:numEntries]

    formattedList=[]
    for element in truncatedList:
        if isinstance(element,Thread):
            formattedList.append(["Thread",element])
        if isinstance(element,Post):
            formattedList.append(["Post",element])
    return formattedList

def getAddedFilesAndVideos(groupCode,courseCode,numEntries):
    courseModel=Course.objects.get(code=courseCode)
    grp=Group.objects.get(code=groupCode,course=courseModel)
    videoList=Video.objects.filter(groups=grp)
    fileList=File.objects.filter(groups=grp)

    addedList=sorted(chain(videoList,fileList),key=lambda instance: instance.date)
    truncatedList=addedList[::-1][0:numEntries]
    formattedList=[]
    for element in truncatedList:
        if isinstance(element,Video):
            formattedList.append(["Video",element])
        if isinstance(element,File):
            formattedList.append(["File",element])
    return formattedList

def getgroupNews(groupCode,courseCode,numEntries):
    courseModel=Course.objects.get(code=courseCode)
    grp=Group.objects.get(code=groupCode,course=courseModel)
    newsList=News.objects.filter(groups=grp).order_by('-date')[0:numEntries]

    return newsList

def lstAverage(lst):
    average = 0
    if not lst:
        return 0
    for elem in lst:
        average+=int(elem)
    average /= float(len(lst))
    return average

def getComment(categName, grade):
    '''
    Receives a string as categName which denotes category and
    a float number which is the grade to search.
    '''
    try:
        comment = FeedbackComment.objects.filter(category=categName).\
                    filter(minGrade__lte=grade).order_by('-minGrade')[0]
    except IndexError:
        comment= ""
    return comment

def getThreadsForGroup(activeGroup):
    return Thread.objects.filter(group=activeGroup).order_by('-date')
        
def getGroupsForUser(user):
    userGroupList=[]
    try:
        userDjangoGroup=user.groups.values()[0]['name']
    except:
        return userGroupList
    if userDjangoGroup == 'Students':
        groupList = Group.objects.all()
        for group in groupList:
            try:
                group.students.get(id=user.id)#username=user.usernam
                userGroupList.append(group)
            except:
                continue

    elif userDjangoGroup == 'Teachers':
        teacherUser=Teacher.objects.get(username=user.username)
        gList = Group.objects.filter(teacher=teacherUser)
        dict = {}
        for group in gList:
            dict[group]=group
        userGroupList = dict.values()
        
    return userGroupList

def getGroup(courseModel, groupCode):
        newGroup = Group.objects.get(
                            Q(course=courseModel), Q(code=groupCode)
                            )
        return newGroup

def registerStudents(fileName, courseKey, courseName, groupKey, teacherUser):
    newGroup=None
    try:
        existentCourse = Course.objects.get(code=courseKey)
        newGroup = getGroup(existentCourse,groupKey)
        
        #if newGroup.teacher == teacherUser:
           # newGroup.delete()
        #else:
           # return "error"
    except:
        pass
    
    try:
        newCourse = Course.objects.get(code=courseKey)
    except:
        newCourse = Course(code=courseKey, name=courseName)
        newCourse.save()
    if not newGroup:
        newGroup = Group(code=groupKey, teacher=teacherUser,course=newCourse)
        newGroup.save()
        
    lstStudentsInfo = getExcelRows(fileName)
    lstStudents =[]
    try:
        g = DjangoGroup.objects.get(name='Students')
    except:
        g = DjangoGroup(name='Students')
        g.save()
        g.permissions.add(Permission.objects.get(codename='add_video'), Permission.objects.get(codename='add_file'))

    for stInfo in lstStudentsInfo:
        try:
            newSt = Student.objects.get(username=stInfo[0].value)
        except:
            newSt=Student(sesionTime=0)
            usrName=str(stInfo[0].value)
            newSt.username=usrName
            newSt.first_name=str(stInfo[1].value)
            newSt.last_name=str(stInfo[2].value)
            newSt.email=str(stInfo[3].value)
            #newSt = Student(username=str(stInfo[0].value),first_name=stInfo[1].value,last_name=stInfo[2].value,email=stInfo[3].value,sesionTime=0)

            #assing default avatar
            filePath="/resources/avatars/default_avatar.jpg"
            path= os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
            completeFilePath= "%s/%s" % (path,filePath)
            (x,y)=get_image_dimensions(completeFilePath)
            newAvatar=Avatar()
            newAvatar.path=filePath
            newAvatar.width=x
            newAvatar.height=y
            newAvatar.save()
            newSt.avatar=newAvatar

            newSt.save()
            newPassword(newSt.username)
            newSt.groups.add(g)
        lstStudents.append(newSt)

        for st in lstStudents:
            newGroup.students.add(st)

def registerGrades(fileName, courseKey2, groupCode):
    path = os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
    filePath = "%s/grades"%(path)
    lstStudentGrades = getExcelRows(fileName, filePath)
    lstLogin = []
    for studentLogin in lstStudentGrades:
        lstLogin.append(studentLogin[0].value)
    lstLogin.pop(0)
    for i in xrange(len(lstLogin)):
        if notIn(studentLogin[0].value):
            studentGradeIndex = StudentGradeIndex(courseKey = courseKey2, groupKey = groupCode, studentLogin = lstLogin[i],index = str(i))
            studentGradeIndex.save()

def notIn(studentLogin):
    try:
        studentGrade = StudentGradeIndex.objects.all()
        for st in studentGrade:
            if studentLogin == st.studentLogin:
                return False
            else:
                pass
        return True
    except:
        return True

def getDisplayGrades(fileName, login, isTeacher, courseCode, groupCode):
    registerGrades(fileName, courseCode, groupCode)
    path = os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
    filePath = "%s/grades"%(path)
    lstStudentGrades = getExcelRows(fileName, filePath)
    lstLogin = []
    for studentLogin in lstStudentGrades:
        lstLogin.append(studentLogin[0].value)
    lstLogin.pop(0)
    studentGradeIndexList = StudentGradeIndex.objects.all()
    alumnoExiste=False
    returnList = []
    for i in xrange(len(studentGradeIndexList)):
        if studentGradeIndexList[i].studentLogin == login:
            alumnoExiste=True
            lst2=getExcelRow(fileName,i+1)
            for a in xrange(len(lst2)):
                returnList.append(lst2[a].value)
        else:
            lst2=getExcelRows(fileName, filePath)
            lst2.pop(0)
            
    if isTeacher:
        return lst2
    if alumnoExiste:
        return returnList
    return "El alumno no existe en la lista"
    
def getExcelRows(fileName, filePathOverride=False):
    if filePathOverride:
        filePath=filePathOverride+"/%s"%(fileName)
        print filePath
    else:
        path = os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
        filePath = "%s/temp/%s"%(path,fileName)
        print filePath


    wb = xlrd.open_workbook(filePath)
    
    s = wb.sheet_by_index(0)
    lstRows=[]
    for r in range(s.nrows):
        lstRows.append(s.row(r))
    return lstRows

def getExcelRow(fileName, rowNumber):
    path = os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
    filePath = "%s/grades/%s"%(path,fileName)
    wb = xlrd.open_workbook(filePath)
    s = wb.sheet_by_index(0)
    return s.row(rowNumber)

#si se le pasa nameOverride, se sutituirá el nombre del archivo original por
# nameOverride. (la terminación se queda igual [.xls, .doc, etc..],
#no hace falta pasarle la terminación en nameOverride
def writeUploadedFile(f, path, nameOverride=False):
    print '    -> destination: '+path+f.name
    if nameOverride:
        fileType=f.name.split('.')[-1]
        destination = open(path+nameOverride+'.'+fileType, 'wb+')
    else:
        destination = open(path+f.name,'wb+')
    
    
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()

def handleUploadedVideo(f):
    isFlv = f.name.endswith(".flv")
            
    path = os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
    fullPath=path+"/videos/"
    
    print '    -> f: '+fullPath+f.name
    if isFlv:
        destination = open(fullPath+f.name,'wb+')
    else:
        destination = open(fullPath+f.name,'wb+')
    for chunk in f.chunks():
        destination.write(chunk)
    destination.close()
    
    if isFlv:
        createVideoThumbnail(f)

def createVideoThumbnail(video):
    
    videoName = video.name[:-3]
    path = os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
    videoInfoCmd = "ffmpeg -i %s/videos/%sflv" % (path,videoName)
    videoInfo = commands.getoutput(videoInfoCmd)
    duration = getVideoHalfDuration(videoInfo)
    grabimage = "ffmpeg -y -i %s/videos/%sflv -vframes 1 -ss %s -an -vcodec png -f rawvideo -s 320x240 %s/videos/thumbnails/%spng" % (path, videoName, duration,path, videoName)
    commands.getoutput(grabimage)

def handleAvi(f, fileModel, protectedVideo):
    flvFileName = f.name[:-3]+'flv'
    aviFileName = f.name[:-3]+'avi'
    path = os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
    ffmpeg = "ffmpeg -y -i %s/files/%s  -ar 22050 -ab 32000 -f flv -s 320x240 %s/videos/%s" % (path, f.name, path, flvFileName)
    print ffmpeg
    try:
        print "before exec ffmpeg"
        x = commands.getoutput(ffmpeg)
        print "executed ffmpeg"
        createVideoThumbnail(f)
        print "made thumb"
        newVideo = Video(title=fileModel.title, description=fileModel.description, filename=flvFileName, date=datetime.datetime.now(), thumbnail=f.name[:-3]+'png',protected=protectedVideo, allGroups=fileModel.allGroups)
        newVideo.save()
        for group in fileModel.groups.all():
            newVideo.groups.add(group)
            
        print "saved to the DB"
        if protectedVideo == 'on':
            fileModel.delete()
            rmCmd = "rm -f %s/files/%s"%(path, aviFileName)
            commands.getoutput(rmCmd)
    except:
        traceback.print_exc()
        print "unexpected exception at  auxiliaries.handleAvi()"

def handleMpg(f, fileModel):
    flvFileName = f.name[:-3]+'flv'
    mpgFileName = f.name[:-3]+'mpg'
    path = os.path.join(os.path.dirname(__file__), 'static').replace('\\','/')
    ffmpeg = "ffmpeg -y -i %s/videos/%s  -ar 22050 -b 128 -s 320x240 %s/videos/mobileVideos/%s" % (path, f.name, path, mpgFileName)
    print ffmpeg
    try:
        print "before exec ffmpeg"
        x = commands.getoutput(ffmpeg)
        print "executed ffmpeg"  
    except:
        traceback.print_exc()
        print "unexpected exception at  auxiliaries.handleMpg()"

def getVideoHalfDuration(videoInfo):
    #Durationformat: 00:05:13.00
    start=videoInfo.rfind("Duration: ")
    durationString = videoInfo[start+10:start+18]
    hours,minutes,seconds=int(durationString[0:2]), int(durationString[3:5]), int(durationString[6:8])
    totalSeconds = (hours*3600) + (minutes*60) + seconds
    totalSeconds /= 2
    midHours = midMinutes = midSeconds = 0
    if totalSeconds/3600:
        midHours = totalSeconds = totalSeconds/3600
    if totalSeconds/60:
        midMinutes = totalSeconds = totalSeconds/60
    midSeconds = totalSeconds
    
    return "%s:%s:%s" % (midHours, midMinutes, midSeconds)

def getHourTimeSession(date):
	hour = ":".join(str(date).split(" ")[1].split(".")[0].split(":")[:2])
	return hour
	
def hourSubstraction(loginHour, logoutHour):
	loginMinutes =0 #loginHour.split(":")[1]
	loginHours =0 #loginHour.split(":")[0]
	logoutMinutes =0 #logoutHour.split(":")[1]
	logoutHours =0# logoutHour.split(":")[0]
	
	subsMin = (int(logoutMinutes) - int(loginMinutes))%60
	subsHour = (int(logoutHours) - int(loginHours))%24
	
	if (subsMin > 45):
		return subsHour + 1
	else:
		return subsHour
	

def calcSessionTimeComment(sessionTime, average=5, course="", group=""):
    print course
    print group
    cat = "SessionTime"
    grade = (float(sessionTime) / float(average)) * 100
    return getComment(grade, cat, course, group)

def calcPostComment(username, course, group):
    try:
        courseModel = Course.objects.get(code = course)
        groupModel = getGroup(courseModel, group)
        threads = Thread.objects.filter(group = groupModel)
        if len(threads)==0:
            return ""
        addRate = 0
        positiveRate = 0
        for thread in threads:
            try:
                posts = Post.objects.filter(thread = thread.id , creator = username)
                if len(posts) == 0:
                    return getComment(0,"PostGrade", course, group)
                for post in posts:
                    print "POST"
                    print post
                    date = post.date
                    if inWeekDate(date,course,group):
                        pstUserVotes = PostUserVote.objects.filter(post = post)
                        for pstUserVote in pstUserVotes:
                            if pstUserVote.voteType:
                                addRate += 1
                                positiveRate += 1
                            else:
                                addRate +=1
                grade = float(positiveRate) / float(addRate)
            except:
                return getComment(100,"PostGrade", course, group)
        return getComment(grade*100,"PostGrade", course, group)
    except:
        return ""

def getComment(grade, cat, course, group):
    gradeComment = 0
    if grade > 100:
        grade = 100
    feedList = FeedbackComment.objects.filter(category = cat, course = course, group = group)
    minGradeList = []
    for feed in feedList:
        minGradeList.append(feed.minGrade)
    minGradeList.sort()
    for i in xrange(len(minGradeList)):
        if grade < minGradeList[i]:
            if i != 0:
                gradeComment = minGradeList[i-1]
                break
            elif i==0:
                gradeComment = minGradeList[i]
                break
        elif grade == minGradeList[i]:
            gradeComment = minGradeList[i]
            break
        elif grade > minGradeList[len(minGradeList)-1]:
            gradeComment = minGradeList[len(minGradeList)-1]

    comment = FeedbackComment.objects.filter(category = cat, minGrade = gradeComment)[0].comment
    return comment


def createPassword(length = 4):
    """Method for creating
       a random password with characters and integers."""
    psw = []
    for i in range(0,length):
        ran = random.randint(0,2)
        if ran == 0:
            psw.append(str(random.randint(0,9)))
        if ran == 1:
            ranLet1 = random.randint(65,90)
            psw.append(str(chr(ranLet1)))
        if ran == 2:
            ranLet2 = random.randint(97,122)
            psw.append(str(chr(ranLet2)))
        psw.append(str(random.randint(0,9)))
    return ''.join(psw)

def sendPasswordToMail(mail, to, password):
    send_mail('New password', '''Your account has been created
    Welcome to codeinn!
    Your password is: %s''' % (password,) , mail, [to], fail_silently=False)

def setPassword(login, password):
    user = User.objects.filter(username = login)[0]
    user.set_password(password)
    user.save()

def sendEmailHomework(courseCode, groupCode, username, subject, message,fromWho, attachment):
    teacherUsername = ((ConstantVariables.objects.filter(course = courseCode, group = groupCode)[0]).teacher).username
    successBar = "No se envi� tu correo satisfactoriamente"
    to = (Teacher.objects.filter(username = teacherUsername)[0]).email
    email = EmailMessage(username + "_" +subject, message, fromWho,
            [to])
    try:
        email.attach_file(attachment)
        email.send()
    except:
        return render_to_response('successMail.html',{"successBar":successBar})

def newPassword(login):
    password = createPassword()
    mail = getUserMail(login)
    setPassword(login, password)
    sendPasswordToMail("open.sender@gmail.com", mail, password)


yearMonths = ['Enero 31',
     'Febrero 28 29',
     'Marzo 31',
     'Abril 30',
     'Mayo 31',
     'Junio 30',
     'Julio 31',
     'Agosto 31',
     'Septiembre 30',
     'Octubre 31',
     'Noviembre 30',
     'Diciembre 31']

def getStrMonth(index):
    return yearMonths[index-1].split(" ")[0]

def weekDays(date2, metricDay):
    """
    This method returns a weekDay format of the next revision date
    """
    date = (date2.encode("utf-8")).split(",")
    dayInt = int(date[1])
    monthInt = int(date[0])
    yearInt = int(date[3])
    week = int(dayInt + metricDay)
    month = yearMonths[monthInt-1].split(" ")
    if monthInt==2 and yearInt%4 == 0:
        if week > int(month[2]):
            week = metricDay - (week-int(month[2]))
            monthInt += 1
    else:
        if monthInt == 2:
            if week > month[2]:
                week = metricDay - (week-int(month[1]))
                monthInt += 1
        elif week > int(month[1]):
            week = metricDay - (week-int(month[1]))
            if monthInt == 12:
                monthInt = 1
            else:
                monthInt += 1
            #Weekdays structure example: [9,23,"Septiembre",2009] that means September 23 2009
    return str(monthInt)+","+str(week)+","+yearMonths[monthInt-1].split(" ")[0]+","+str(yearInt)

def inWeekDate(date,course, group):
    """
    This method calculates if a DateTime field (date) is in the current weekDayEnd revision
    """
    const = ConstantVariables.objects.filter(course = course, group = group)[0]
    weekDay = const.weekDayEnd
    metricDay = const.metricDay
    toIntDay = int((weekDay.split(","))[1])
    toIntMonth = int((weekDay.split(","))[0])
    start = toIntDay - metricDay
    print "prueba f"
    if date.month == toIntMonth:
        print "prueba g"
        if start > 0:
            if date.day >= start and date.day < toIntDay:
                print "prueba h"
                return True
            else:
                return False
    elif date.month == toIntMonth -1:
        print "prueba j"
        if start < 0:
            dif = abs(start)
            allMonthDays = int(yearMonths[toIntMonth-1].split(" ")[1])
            start = allMonthDays - dif
            if date.day > start or date.day < toIntDay:
                return True
            else:
                return False
    else:
        print "prueba k"
        return False



def inWeek(today, weekDays):
    """Method that returns True if the datetime object "today" is
    in a certain week in a "weekDays" format. False if doesn�t
    """
    dayInt = int(str(today).split(" ")[0].split("-")[2])
    monthInt = int(str(today).split(" ")[0].split("-")[1])
    toIntMonth = int((weekDays.split(","))[0])
    toIntDay = int((weekDays.split(","))[1])
    if monthInt == toIntMonth-1 and toIntMonth != 1:
        return True
    if monthInt == 12 and toIntMonth == 1:
        return True
    if monthInt == toIntMonth:
        if dayInt <= toIntDay:
            return True
        else:
            return False
    else:
        return False

def frontWeek(today, weekDays2):
    """
    This method returns True if today is in front of the weekDays2 (weekDay format) revision in a calendar
    """
    weekDays = (weekDays2.encode("utf-8")).split(",")
    dayInt = int(str(today).split(" ")[0].split("-")[2])
    monthInt = int(str(today).split(" ")[0].split("-")[1])
    
    # ERROR: invalid literal for int() with base 10: ''
    toIntMonth = int(weekDays[0])
    toIntDay = int(weekDays[1])
    if monthInt == toIntMonth:
        if dayInt > toIntDay:
            return True
        else:
            return False
    elif monthInt == 1 and toIntMonth==12:
        return True
    elif monthInt > toIntMonth:
        return True
    else:
        return False

def translateDay(toDay):
    if toDay == "Sun":
        return "Domingo"
    elif toDay == "Mon":
        return "Lunes"
    elif toDay == "Tue":
        return "Martes"
    elif toDay == "Wed":
        return "Miercoles"
    elif toDay == "Thu":
        return "Jueves"
    elif toDay == "Fri":
        return "Viernes"
    elif toDay == "Sat":
        return "Sabado"
    else:
        return ""
def translateMonth(toMonth):
    if toMonth == "Jan":
        return "Enero"
    elif toMonth == "Feb":
        return "Febrero"
    elif toMonth == "Mar":
        return "Marzo"
    elif toMonth == "Apr":
        return "Abril"
    elif toMonth == "May":
        return "Mayo"
    elif toMonth == "Jun":
        return "Junio"
    elif toMonth == "Jul":
        return "Julio"
    elif toMonth == "Aug":
        return "Agosto"
    elif toMonth == "Sep":
        return "Septiembre"
    elif toMonth == "Oct":
        return "Octubre"
    elif toMonth == "Nov":
        return "Noviembre"
    elif toMonth == "Dec":
        return "Diciembre"
    else: 
        return ""

def respondToMobile(message):
	response = HttpResponse()
	response.write(message)
    	response['Content-type'] = "text/plain; charset=UTF-8"
    	response['Content-length'] = len(response.content)
    	return response
